using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PoolBase : MonoBehaviour
{
    //资源自动释放时间/秒
    protected float m_ReleaseTime;
    //上次释放资源的时间/毫微秒 1s = 1000ms = 1000,000us
    protected long m_LastReleaseTime;
    //对象池
    protected List<PoolObject> m_Pool;

    //初始化对象池
    public void Init(float releaseTime)
    {
        m_ReleaseTime = releaseTime;
        m_Pool = new List<PoolObject>();
    }

    private void Start()
    {
        m_LastReleaseTime = System.DateTime.Now.Ticks;
    }

    //获取对象
    public virtual Object Spwan(string name)
    {
        foreach (PoolObject poolObject in m_Pool)
        {
            if(poolObject.Name == name)
            {
                //池子中的对象是没有用的，正在使用的对象是不会放入池子中的
                m_Pool.Remove(poolObject);
                return poolObject.Object;
            }
        }
        return null;
    }

    //回收对象
    public virtual void UnSpwan(string name, Object obj)
    {
        m_Pool.Add(new PoolObject(obj, name));
    }

    //释放函数，再update中定期调用
    public virtual void Release()
    {

    }

    //定期释放
    private void Update()
    {
        if (System.DateTime.Now.Ticks - m_LastReleaseTime >= m_ReleaseTime * 10000000)
        {
            Release();
            m_LastReleaseTime = System.DateTime.Now.Ticks;
        }
    }
}
